package com.chenl.provider.util;

import com.sun.org.apache.xpath.internal.operations.Bool;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.regex.Pattern;

public class StrUtils {
    /**
     * 查找str字符中,findStr字符第countIndex次出现的位置,没有就返回-1
     * @param str
     * @param findStr
     * @param countIndex
     * @return
     */
    public static Integer findIndexFromStr(String str,String findStr,Integer countIndex){
        int index=-1;
        for (int i = 0; i < countIndex; i++) {
            index = str.indexOf(findStr, index + 1);
            if (index == -1) {
                break;
            }
        }
        return index;
    }



    /**
     * 查找字符target在字符串text中倒数第n次出现的位置
     * @param text
     * @param target
     * @param n
     * @return
     */
    public static int findLastIndexof(String text, char target, int n) {
        int count = 0;
        int lastIndex = -1;
        for (int i = text.length() - 1; i >= 0; i--) {
            if (text.charAt(i) == target) {
                count++;
                if (count == n) {
                    lastIndex = i;
                    break;
                }
            }
        }
        return lastIndex;
    }
    /**
     * 正则表达式校验
     */
    public static Boolean strVerify(String str,String regex){
        return Pattern.compile(regex).matcher(str).find();
    }


    /**
     * 校验常用正则
     */
    public enum RegexEnum {
        ID_CARD("^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$"),

        PHONE("(^1[1-9](\\d{9}))|(\\d{3,4}-\\d{7,8})$"),

        EMAIL("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?"),

        BANK_NO("^([1-9]{1})(\\d{13,19})$"),

        SOCIAL_CREDIT_CODE("(^(?:(?![IOZSV])[\\dA-Z]){2}\\d{6}(?:(?![IOZSV])[\\dA-Z]){10}$)|(^\\d{15}$)"),

        FACTORY_ORG_CODE("^([A-Za-z0-9]{1})([A-Za-z0-9]{1})$"),

        IS_NUMBER("^\\d+$"),

        CONTAIN_CHINESE("[\\\\u4e00-\\\\u9fa5]+"),
        ONLY_CONTAIN("^[,0-9]+$")
        ;

        /**
         * 正则表达式
         */
        private String regex;


        RegexEnum(String regex) {
            this.regex = regex;
        }


        public String getRegex() {
            return regex;
        }

        /**
         * 验证各种号码是否合法
         * @param value
         * @return
         */
        public static Boolean verify(String value, RegexEnum regex) {
            boolean valid = Pattern.compile(regex.getRegex()).matcher(value).find();
            if(!valid) {
                return Boolean.FALSE;
//                throw new RuntimeException("校验不通过");
            }
            return Boolean.TRUE;
        }
    }


}
